package com.xdclass.synchronizeds;

/**
 * @Author: Timo
 * @Date: 2019/4/26 16:56
 * @Description: 测试synchronized修饰
 * 普通方法
 * 静态方法
 * 代码块
 * 的区别
 */
public class SynchronizedDemo implements Runnable {
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName());
    }

    /**
     * @return void
     * @Author: timo
     * @Date: 2019/4/26 17:21
     * @Description: 普通方法前面加个synchronized
     * 只是锁住了对象实例，每个对象实例之间的线程互不干扰
     */
    public synchronized void out() throws InterruptedException {
        System.out.println(Thread.currentThread().getName()+"   Test synchronized modification  ordinary method");
        Thread.sleep(3000L);
    }



    /**
     * @return void
     * @Author: timo
     * @Date: 2019/4/26 17:21
     * @Description: 静态方法前面加个synchronized
     * 锁住的是整个类，只要有一个线程再使用
     */
//    public static synchronized void out() throws InterruptedException {
//        System.out.println("Test synchronized modification  static method");
//        Thread.sleep(3000L);
//    }

    public void out1() {
        System.out.println("<><><><>");
    }



    public static void main(String[] args) {
        SynchronizedDemo synchronizedDemo1 = new SynchronizedDemo();
        SynchronizedDemo synchronizedDemo2 = new SynchronizedDemo();

        new Thread(() -> {
            try {
                synchronizedDemo1.out();
                synchronizedDemo1.out1();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        new Thread(() -> {
            try {
                synchronizedDemo2.out();
                synchronizedDemo2.out1();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

    }
}
